<!-- 用户资料页 -->
<template>
	<view class="uni-content">
		<view class="avatar">

      <button open-type="chooseAvatar" @chooseavatar="bindchooseavatar" @click="uploadAvatarImg" class="box showBorder"   style="padding: 0; width: 260rpx;height: 260rpx;line-height: 260rpx;">
        <!--aspectFill、aspectFit、bottom、bottom left、bottom right、center、heightFix、left、right、scaleToFill、top、top left、top right或widthFix-->
        <cloud-image v-if="userInfo.img!=''"  :src="userInfo.img" :mode="'scaleToFill'" width="260rpx" height="260rpx"></cloud-image>
        <uni-icons v-else style="width: 260rpx;height: 260rpx;line-height: 260rpx;" class="chooseAvatar" type="plusempty" size="30"
                   color="#dddddd"></uni-icons>
      </button>
		</view>


		<uni-list>

      <uni-list-item class="item" @click="setNickname('')" title="昵称" :rightText="userInfo.name||'未设置'" link>
			</uni-list-item>

      <uni-list-item class="item"  @click="bindPhone(userInfo.user_tel)" title="手机号" :rightText="userInfo.user_tel||'未绑定,点击绑定'" link >
			</uni-list-item>


			<uni-list-item v-if="hasPwd" class="item" @click="changePassword(1)" title="修改登录密码" link>
      </uni-list-item>
			<uni-list-item v-if="!hasPwd" class="item" @click="changePassword(0)" title="设置登录密码" link>
			</uni-list-item>

		</uni-list>

		<!--&lt;!&ndash; #ifndef MP &ndash;&gt;-->
		<!--<uni-list class="mt10">-->
		<!--	<uni-list-item @click="deactivate" title="注销账号" link="navigateTo"></uni-list-item>-->
		<!--</uni-list>-->
		<!--&lt;!&ndash; #endif &ndash;&gt;-->

		<!--<uni-popup ref="dialog" type="dialog">-->
    <!--  <input type="nickname" @blur="nicknameBlur">-->
		<!--</uni-popup>-->

		<uni-popup ref="dialog" type="dialog">
			<uni-popup-dialog mode="input" :value="userInfo.nickname" @input="nicknameInput" @blur="nicknameBlur" @confirm="setNickname" :inputType="setNicknameIng?'nickname':'text'"
				title="设置昵称" placeholder="请输入要设置的昵称">
			</uni-popup-dialog>
		</uni-popup>


		<template v-if="showLoginManage">
			<button v-if="userInfo.id" @click="logout">退出登录</button>
		</template>

	</view>
</template>
<script>
import {mutations as uniIdMutations} from '@/uni_modules/uni-id-pages/common/store.js'
var app = getApp();
  import {
    mutations
  } from '@/uni_modules/uni-id-pages/common/store.js'
	export default {
		data() {
			return {
				univerifyStyle: {
					authButton: {
						"title": "本机号码一键绑定", // 授权按钮文案
					},
					otherLoginButton: {
						"title": "其他号码绑定",
					}
				},
				userInfo: {
					mobile:'',
					name:''
				},
        hasPwd: false,
				showLoginManage: false ,//通过页面传参隐藏登录&退出登录按钮
				setNicknameIng:false
			}
		},
		async onShow() {
      this.load_user_info()
		},
		async onLoad(e) {
			if (e.showLoginManage) {
				this.showLoginManage = true //通过页面传参隐藏登录&退出登录按钮
			}
			//判断当前用户是否有密码，否则就不显示密码修改功能
			this.load_user_info()
		},
		methods: {
      async bindchooseavatar(res){
        let avatarUrl = res.detail.avatarUrl
        let avatar_file = {
          extname: avatarUrl.split('.')[avatarUrl.split('.').length - 1],
          name:'',
          url:''
        }
        //上传到服务器
        let cloudPath = this.userInfo.id + '' + Date.now()
        avatar_file.name = cloudPath
        try{
          uni.showLoading({
            title: "更新中",
            mask: true
          });
          let {
            fileID
          } = await uniCloud.uploadFile({
            filePath:avatarUrl,
            cloudPath,
            fileType: "image"
          });
          avatar_file.url = fileID
          uni.hideLoading()
        }catch(e){
          console.error(e);
        }
        console.log('avatar_file',avatar_file);
        this.setAvatarFile(avatar_file)
      },

      uploadAvatarImg(res) {
        // #ifdef MP-WEIXIN
        return false // 微信小程序走 bindchooseavatar方法
        // #endif

        // #ifndef MP-WEIXIN
        const crop = {
          quality: 100,
          width: 600,
          height: 600,
          resize: true
        };
        uni.chooseImage({
          count: 1,
          crop,
          success: async (res) => {
            let tempFile = res.tempFiles[0],
                avatar_file = {
                  // #ifdef H5
                  extname: tempFile.name.split('.')[tempFile.name.split('.').length - 1],
                  // #endif
                  // #ifndef H5
                  extname: tempFile.path.split('.')[tempFile.path.split('.').length - 1]
                  // #endif
                },
                filePath = res.tempFilePaths[0]

            let cloudPath = this.userInfo.id + '' + Date.now()
            avatar_file.name = cloudPath
            uni.showLoading({
              title: "更新中",
              mask: true
            });


            let {
              fileID
            } = await uniCloud.uploadFile({
              filePath,
              cloudPath,
              fileType: "image"
            });
            avatar_file.url = fileID
            uni.hideLoading()
            this.setAvatarFile(avatar_file)
          }
        })
        // #endif
      },

      setAvatarFile(avatar_file) {
        console.log("头像文件",avatar_file)
        //avatar_file.url:"https://mp-7eae9bec-3fc9-47f2-a998-0e5615542f89.cdn.bspapp.com/cloudstorage/67256a66-4ed6-44b0-946c-b51b14eac19e."
        app.globalData.util.request({
            url: 'entry/wxapp/update_user_userinfo',
            cachetime: '0',
            data: {
              avatar: avatar_file.url
            },
            success: (t)=> {
              this.userInfo=t.data.data
              //判断是否有密码
              if (this.userInfo.user_pass!="") {
                this.hasPwd = true
              }else{
                this.hasPwd = false
              }
              //更新缓存
              uni.setStorageSync('users', this.userInfo)
            }
        })
      },

      load_user_info(){
        var h = uni.getStorageSync('users').id
        app.globalData.util.request({
          url: 'entry/wxapp/UserInfo',
          cachetime: '0',
          data: {
            user_id: h
          },
          success: (t)=> {
            this.userInfo=t.data
            //判断是否有密码
            if (this.userInfo.user_pass) {
              this.hasPwd = true
            }else{
              this.hasPwd = false
            }
            //更新缓存
            uni.setStorageSync('users', this.userInfo)
          }
        })
      },

			logout() {
        //退出用户身份
        this.userInfo = null
        app.globalData.token = null
        uni.removeStorageSync('dy-token')
        uni.removeStorageSync('users')
        uni.removeStorageSync('user_is_login')

        //退出商家身份
        uni.removeStorageSync('store_is_login')
        uni.removeStorageSync('sjdsjid')

        //退出uni-id身份
        uniIdMutations.logout()

        uni.$u.toast("退出成功");
        //     未登录,跳转到登录页面
        uni.reLaunch({
          url: '/ymq_canyino2o/pages/my2/index?is_show_login=1',
          fail: (e) => {
            uni.reLaunch({
              url: '/ymq_canyino2o/pages/my2/index?is_show_login=1',
            })
          }
        })
			},

			bindMobileSuccess() {
				mutations.updateUserInfo()
			},

			changePassword(hasPwd) {
				uni.navigateTo({
					url: '/ymq_canyino2o/pages/my/change_pwd?hasPwd=' + hasPwd,
					complete: (e) => {
						// console.log(e);
					}
				})
			},
      nicknameInput(e) {
        console.log("nickname nicknameInput",e)
        // this.userInfo.nickname=nickname
      },
      nicknameBlur(e){
        let nickname = e.detail.value
        if (nickname) {
          this.setNickname(nickname)
        }
        console.log("nickname nicknameBlur",nickname)
        // this.userInfo.nickname=nickname
      },

      // 绑定手机号
      bindPhone(phone) {
        console.log("绑定手机号")
        uni.navigateTo({
          url: '/ymq_canyino2o/pages/my/bindPhone?phone='+phone,
          complete: (e) => {
            // console.log(e);
          }
        })
      },

			setNickname(nickname) {
        console.log("设置昵称",nickname)
				if (nickname) {
          app.globalData.util.request({
            url: 'entry/wxapp/update_user_userinfo',
            cachetime: '0',
            data: {
              name: nickname
            },
            success: (t)=> {
              this.userInfo=t.data.data
              //判断是否有密码
              if (this.userInfo.user_pass!="") {
                this.hasPwd = true
              }else{
                this.hasPwd = false
              }

              this.setNicknameIng = false
              this.$refs.dialog.close()

              this.load_user_info()

            }
          })
				} else {
          // #ifdef MP-WEIXIN
          this.setNicknameIng=true
          // #endif
					this.$refs.dialog.open()
				}
			},

		}
	}
</script>
<style lang="scss" scoped>
	@import "@/uni_modules/uni-id-pages/common/login-page.scss";

	.uni-content {
		padding: 0;
	}

	/* #ifndef APP-NVUE */
	view {
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
	}

	@media screen and (min-width: 690px) {
		.uni-content {
			padding: 0;
			max-width: 690px;
			margin-left: calc(50% - 345px);
			border: none;
			max-height: none;
			border-radius: 0;
			box-shadow: none;
		}
	}

	/* #endif */
	.avatar {
		align-items: center;
		justify-content: center;
		margin: 22px 0;
		width: 100%;
	}

	.item {
		flex: 1;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	button {
		margin: 10%;
		margin-top: 40px;
		border-radius: 0;
		background-color: #FFFFFF;
		width: 80%;
	}

	.mt10 {
		margin-top: 10px;
	}
</style>
